package com.tcwlkj.uuService.ui.login;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tcwlkj.uuService.MainActivity;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.HttpIp;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.UpDateVersionModel;
import com.tcwlkj.uuService.model.UpdateMessage;
import com.tcwlkj.uuService.model.checkModel;
import com.tcwlkj.uuService.ui.BaseActivity;
import com.tcwlkj.uuService.ui.SettingActivity;
import com.tcwlkj.uuService.update.DownLoadService;
import com.tcwlkj.uuService.utils.CommomDialog;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/10/9 0009.
 * 启动页面
 */

public class WelcomeActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.iv_entry)
    ImageView mIVEntry;
    @Bind(R.id.ll_pb)
    LinearLayout ll_pb;
    private String update = "0";
    private String currentVersion;
    private String newVersion;
    private Intent ServiceIntent;
    private static final float SCALE_END = 1.0F;
    private static final int ANIM_TIME = 2000;
    private Dialog dialog;
    private ProgressDialog progressDialog;
    private boolean isBound = false;
    private Intent updateService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        UpDateVersion();
    }
    private void UpDateVersion() {
        Call<CommonResponse<checkModel>> httpResultCall = RetrofitUtils.getRequest(WelcomeActivity.this,false).check("13", "10",Tools.getVersion(this));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<checkModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse commonResponse= (CommonResponse) t;
                checkModel check= (checkModel) commonResponse.getData();
                if(check.getForce().equals("0")){//自主更新
                    version(check.getVersion(),check.getUpNote(),check.getDownLink());//版本升级
                }else {//强制更新
                    mustVersion(check.getVersion(),check.getUpNote(),check.getDownLink());//版本升级
                }
            }
            @Override
            public void onFail(int code, String message) {
                if (PreferencesUtils.getBoolean(WelcomeActivity.this, "Login")) {
                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    startMainActivity();
                }
            }
        });
    }

    private void version(String version,String upNote,String DownLink) {
        CommomDialog commomDialog=new CommomDialog(WelcomeActivity.this, R.style.dialog, "最新版本：V " + version+"\n"+upNote, new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                if (EasyPermissions.hasPermissions(WelcomeActivity.this, perms)) {
                    updateService = new Intent(WelcomeActivity.this, DownLoadService.class);
                    updateService.putExtra("url", DownLink);
                    isBound=bindService(updateService,conn, Context.BIND_AUTO_CREATE);
                    startService(updateService);
                    initProgress();
                }else {
                    EasyPermissions.requestPermissions(WelcomeActivity.this, "需要读取文件权限",
                            1, perms);
                }
            }
        },new CommomDialog.OnCancelsListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {

                if (PreferencesUtils.getBoolean(WelcomeActivity.this, "Login")) {
                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    startMainActivity();
                }
            }
        }).setTitle("版本升级");
        commomDialog.show();
        commomDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });

    }

    private void mustVersion(String version,String upNote,String DownLink){
        CommomDialog commomDialog= new CommomDialog(WelcomeActivity.this, R.style.dialog, "最新版本：V " + version+"\n"+upNote, new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                if (EasyPermissions.hasPermissions(WelcomeActivity.this, perms)) {
                        updateService = new Intent(WelcomeActivity.this, DownLoadService.class);
                        updateService.putExtra("url", DownLink);
                        isBound=bindService(updateService,conn, Context.BIND_AUTO_CREATE);
                        startService(updateService);
                        initProgress();
                    }else {
                    EasyPermissions.requestPermissions(WelcomeActivity.this, "需要读取文件权限",
                            1, perms);
                }

            }
        }).setTitle("版本升级");
        commomDialog.show();

        commomDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                commomDialog.dismiss();
                finish();
                return false;
            }
        });
        commomDialog.setCancleVisibility(false);
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            DownLoadService downLoadService = ((DownLoadService.MsgBinder)service).getService();
            downLoadService.setOnProgressListener(new DownLoadService.OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    progressDialog.setProgress(progress);
                }
                @Override
                public void cancleProgress() {
                    progressDialog.dismiss();
                    finish();
                }
            });
        }
    };

    public void initProgress(){
        progressDialog = new ProgressDialog(WelcomeActivity.this);
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
    }
    private void startMainActivity() {
        startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
        WelcomeActivity.this.finish();
    }
    private void startAnim() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mIVEntry, "scaleX", 1f, SCALE_END);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mIVEntry, "scaleY", 1f, SCALE_END);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(ANIM_TIME).play(animatorX).with(animatorY);
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
                WelcomeActivity.this.finish();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if(isBound){
            unbindService(conn);
            stopService(updateService);
            isBound=false;
        }
        ButterKnife.unbind(this);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (PreferencesUtils.getBoolean(WelcomeActivity.this, "Login")) {
            Intent intent1 = new Intent(WelcomeActivity.this, MainActivity.class);
            startActivity(intent1);
            WelcomeActivity.this.finish();
        } else {
            startMainActivity();
        }
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("权限设置")
                    .setPositiveButton("设置")
                    .setRationale("当前应用缺少必要权限,可能会造成部分功能受影响！请点击\"设置\"-\"权限\"-打开所需权限。最后点击两次后退按钮，即可返回")
                    .build()
                    .show();
        }
    }
}
